
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author leehoa
 */
public class configJson {
    
    static String filename = "infor.properties";
    
    public static void main(String []agr) throws Exception{
        
        String  t = readConfig(filename, "mysqlserver");
        System.out.println(t);
        
        if(writeConfig(filename, "mysqldb", "127.0.0.1")){
            System.out.println("ok");
        }
        
    }
    
        public static boolean writeConfig(String fname,String key, String value) throws JSONException{
            try{
                File file = new File(fname);
                if(file.exists()){
                    FileInputStream input = new FileInputStream(file);
                    byte [] readbyte = new byte[input.available()];                
                    input.read(readbyte);                                                                            
                    String jsonString = new String(readbyte,"UTF-8");
                    JSONObject jsonObject = new JSONObject(jsonString);
                    jsonObject.remove(key);
                    jsonObject.put(key, value);                    
                    String out = jsonObject.toString();                                        
                    FileOutputStream output = new FileOutputStream(file);
                    output.write(out.getBytes("UTF-8"));  
                    return true;
                }
            }catch(Exception ex){
            }
            return false;
        }
        public static String readConfig(String fname, String key)throws Exception{
            try{
                File file = new File(fname);
                if(file.exists()){
                    FileInputStream input = new FileInputStream(file);
                    byte [] readbyte = new byte[input.available()];                
                    input.read(readbyte);                                                                            
                    String jsonString = new String(readbyte,"UTF-8");
                    JSONObject jsonObject = new JSONObject(jsonString);
                    String value = jsonObject.getString(key);
                    return value;  
                }                                                                              
            }catch(Exception ex){
            }
            return null;
        }    
    
}
